package com.atguigu.daijia.rules.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.daijia.model.entity.rule.ProfitsharingRule;
import com.atguigu.daijia.model.form.rules.ProfitsharingRuleRequest;
import com.atguigu.daijia.model.form.rules.ProfitsharingRuleRequestForm;
import com.atguigu.daijia.model.vo.rules.ProfitsharingRuleResponse;
import com.atguigu.daijia.model.vo.rules.ProfitsharingRuleResponseVo;
import com.atguigu.daijia.rules.helper.DroolsHelper;
import com.atguigu.daijia.rules.mapper.ProfitSharingRuleMapper;
import com.atguigu.daijia.rules.service.ProfitSharingRuleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class ProfitSharingRuleServiceImpl implements ProfitSharingRuleService {

    @Resource
    private ProfitSharingRuleMapper profitsharingRuleMapper;


    /**
     * 计算系统分账费用
     *
     * @param profitSharingRuleRequestForm 分账规则请求表单
     */
    @Override
    public ProfitsharingRuleResponseVo calculateOrderProfitSharingFee(ProfitsharingRuleRequestForm profitSharingRuleRequestForm) {
        // 封装传入对象
        ProfitsharingRuleRequest profitSharingRuleRequest = new ProfitsharingRuleRequest();
        profitSharingRuleRequest.setOrderAmount(profitSharingRuleRequestForm.getOrderAmount());
        profitSharingRuleRequest.setOrderNum(profitSharingRuleRequestForm.getOrderNum());
        log.info("传入参数：{}", JSON.toJSONString(profitSharingRuleRequest));

        // 获取最新订单费用规则
        ProfitsharingRule profitsharingRule = profitsharingRuleMapper.selectOne(new LambdaQueryWrapper<ProfitsharingRule>()
                .orderByDesc(ProfitsharingRule::getId)
                .last("limit 1"));
        KieSession kieSession = DroolsHelper.loadForRule(profitsharingRule.getRule());

        // 封装返回对象
        ProfitsharingRuleResponse profitSharingRuleResponse = new ProfitsharingRuleResponse();
        kieSession.setGlobal("profitsharingRuleResponse", profitSharingRuleResponse);
        // 设置订单对象
        kieSession.insert(profitSharingRuleRequest);
        // 触发规则
        kieSession.fireAllRules();
        // 中止会话
        kieSession.dispose();
        log.info("计算结果：{}", JSON.toJSONString(profitSharingRuleResponse));

        // 封装返回对象
        ProfitsharingRuleResponseVo profitSharingRuleResponseVo = new ProfitsharingRuleResponseVo();
        profitSharingRuleResponseVo.setProfitsharingRuleId(profitsharingRule.getId());
        BeanUtils.copyProperties(profitSharingRuleResponse, profitSharingRuleResponseVo);

        return profitSharingRuleResponseVo;
    }
}
